package com.itheima.auth.handle;

import com.alibaba.fastjson.JSONObject;
import com.itheima.utils.JwtTokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //登入账户信息
        String username = ((UserDetails) authentication.getPrincipal()).getUsername();
        //生成token
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("flag",true);
            jsonObject.put("data", JwtTokenUtil.createToken(username));
            jsonObject.put("message","");
            httpServletResponse.getWriter().write(jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
            httpServletResponse.getWriter().write(e.getMessage());
        }
    }


}
